const Sequelize = require('sequelize');
const _ = require('lodash');
const axios = require('axios');

module.exports = function (storage, config) {
    let {models: {UsersAccounts, UsersAccountsLogs}} = storage;

    let instanceByCookie = function (cookie) {
        return axios.create({
            timeout: 3000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36',
                'Cookie': cookie.cookies
            }
        });
    }

    let testTaobaoCookies = function (instance, cookie) {
        return instance.get('https://cart.taobao.com/json/GetPriceVolume.do?sellerId=0').then(function (response) {
            let data = response.data;
            if (_.isObject(data)) {
                return true;
            }
            if (cookie) {
                console.log('Cookie失效', cookie);

                UsersAccountsLogs.create({
                    opt: 'deactivate',
                    domain: 'taobao.com',
                    username: cookie.username
                });
                UsersAccounts.update({status: 'Deactivated'}, {where: {id: cookie.id}});
            }
            return false;
        });
    }

    return {
        testTaobaoCookies: testTaobaoCookies,
        getInstance: function (where) {
            where.status = 'Active';
            return UsersAccounts.findOne({where: where, order: [Sequelize.fn('RAND')]}).then(function (cookie) {
                if (!cookie) {
                    console.log('获取Cookie失败', JSON.stringify(where));
                    return {};
                }
                return {
                    cookie: cookie,
                    instance: instanceByCookie(cookie)
                };
            });
        }
    }
};